package com.example.consumptionrecords.config.shiro;

import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import java.io.Serializable;

/**
 * 自定义SessionManager，实现无状态 Session 验证
 * 孙敬佳
 * 2024 \ 02 \ 26
 */

public class SessionManager extends DefaultWebSessionManager {

	// 请求头中token的名字
	private static final String AUTHORIZATION = "Authorization";

	// 表示当前 Subject 的请求没有 Session
	private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

	public SessionManager() {
		super();
	}

	@Override
	protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
		// 从 header 里获取sessionId
		String sessionId = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
		//如果请求头中有 Authorization 则其值为sessionId
		if (sessionId != null && sessionId.length() > 0) {
			// 确保引用sessionId
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
			// 将sessionId作为request的属性值
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
			// 确保从请求头中获取的sessionId是有效的
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
			// 重定向之后禁止重写url添加新的JSESSIONID
			request.setAttribute(ShiroHttpServletRequest.SESSION_ID_URL_REWRITING_ENABLED, this.isSessionIdUrlRewritingEnabled());
			return sessionId;
		} else {
			//否则按默认规则从cookie取sessionId
			return super.getSessionId(request, response);
		}
	}
}
